import Axios from "axios";
import Public from "../plugins/public";


function extract() {
    this.init();
}

// 请求加载动画
let loadinginstace;

extract.prototype = {
    // 初始化
    init() {},

    //获取微信验证
    wxShare() {
        if (Public.getCookie('wxCode') && Public.getCookie('isWxCode') == 0) {
            return this.wxMessage()
        } else {
            Public.getQueryString('code') ? this.wxCode() : this.wxCodeUrl()
        }
    },
    // 通过接口获取code  code重定向在url
    wxCodeUrl() {
        Axios.get('/zk/app/crmconfig/getConfig') //获取微信权限
            .then(res => {
                let appId = res.data.data.appId
                let url = encodeURIComponent(window.location.href)
                let pages = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${url}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
                //我是用的非静默授权，snsapi_userinfo 需要用户手动同意
                window.location.replace(pages)
            })
    },
    //url检测是否包含code
    wxCode() {
        Public.setCookie('wxCode', Public.getQueryString('code'))
        Public.setCookie('isWxCode', 0)
        let urlPath = window.location.href;
        if (urlPath.indexOf('&code') != -1) {
            urlPath = urlPath.split('&code')[0]
        }
        window.location.href = decodeURIComponent(urlPath)
    },
    //微信返回的信息
    wxMessage() {
        return new Promise((resolve, reject) => {
            Axios.get(`/zk/api/authorization/getInfo?code=${Public.getCookie('wxCode')}`)
                .then(res => {
                    // console.log(res);
                    if (res.data.code == 0) {
                        sessionStorage.setItem('userWxData', JSON.stringify(res.data.data))

                        Public.setCookie('isWxCode', 1)
                        resolve(res.data.data)
                    }
                })
        })
    }
}

export default new extract();